package com.pet_service.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pet_service.entity.PetInfo;
import com.pet_service.entity.User;
import com.pet_service.result.Result;
import com.pet_service.service.PetInfoService;
import com.pet_service.service.UserService;
import com.pet_service.vo.PageBean;
import com.pet_service.vo.PageResultVO;
import com.pet_service.vo.UserWithPetsVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 邹全伸
 * @version 1.0
 * @date 2025-10-02 09:21
 */
@RestController
@Slf4j
@RequestMapping("/pet")
@Tag(name = "宠物管理")
public class PetController {
    @Resource
    private PetInfoService petInfoService;
    @Resource
    private UserService userService;

    //根据用户id查询该用户的宠物信息
    @GetMapping("/user/{userId}/pets")
    @PreAuthorize("hasAuthority('customer:pet:view')")
    public Result<UserWithPetsVO> getUserWithPets(@PathVariable Integer userId) {
        User user = userService.getById(userId);
        if (user == null) {
            // 也可返回 Result.fail 并自定义错误信息
            throw new RuntimeException("用户不存在");
        }

        List<PetInfo> petList = petInfoService.lambdaQuery()
                .eq(PetInfo::getUser_id, userId)
                .list();

        UserWithPetsVO userWithPetsVO = new UserWithPetsVO(user, petList);
        // 用 Result 封装后返回
        return Result.ok(userWithPetsVO);
    }

    //分页查询所有宠物信息
    @PostMapping("/list")
    @PreAuthorize("hasAuthority('customer:pet:view')")
    public Result<PageResultVO<UserWithPetsVO>> getPetList(@RequestBody PageBean pageBean) {
        // 创建分页对象
        Page<User> page = new Page<>(pageBean.getPageNum(), pageBean.getPageSize());

        // 创建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        String query = pageBean.getQuery();
        if (query != null && !query.trim().isEmpty()) {
            try {
                Integer userId = Integer.parseInt(query.trim());
                queryWrapper.eq("id", userId);
            } catch (NumberFormatException e) {
                queryWrapper.like("username", query.trim())
                        .or()
                        .like("nickname", query.trim());
            }
        }

        // 分页查询用户
        IPage<User> iPage = userService.page(page, queryWrapper);
        List<User> userList = iPage.getRecords();

        // 组装用户-宠物数据
        List<UserWithPetsVO> result = new ArrayList<>();
        for (User user : userList) {
            List<PetInfo> petList = petInfoService.lambdaQuery()
                    .eq(PetInfo::getUser_id, user.getId())
                    .list();
            result.add(new UserWithPetsVO(user, petList));
        }

        // 返回分页结果
        return Result.ok(new PageResultVO<>(Long.valueOf(iPage.getTotal()), result, pageBean));
    }


}
